package datasource.temp;

import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.contentstream.operator.OperatorName;

import java.util.List;

public class TextRemover {
    private boolean textRemoved = false;
    private String textToRemove;

    public void setTextToRemove(String textToRemove) {
        this.textToRemove = textToRemove;
    }

    public boolean processOperator(Operator operator, List<COSBase> operands) {
        String operatorName = operator.getName();
        if (operatorName.equals(OperatorName.SHOW_TEXT) ||
                operatorName.equals(OperatorName.SHOW_TEXT_LINE) ||
                operatorName.equals(OperatorName.SHOW_TEXT_LINE_AND_SPACE)) {
            COSBase base = operands.get(0);
            if (base instanceof COSString) {
                COSString cosString = (COSString) base;
                String text = cosString.getString();
                if (!textRemoved && text.contains(textToRemove)) {
                    String modifiedText = text.replaceFirst(textToRemove, "");
                    if (!modifiedText.isEmpty()) {
                        operands.set(0, new COSString(modifiedText));
                    } else {
                        return false; // 如果文本为空，跳过该操作符
                    }
                    textRemoved = true;
                }
            }
        }
        return true;
    }
}
